<template>
  <a-modal v-model:visible="isShow" title="媒体库信息" okText="保存" @ok="doSave" :confirmLoading="loading">
    <a-form ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="媒体库名称" name="name">
        <a-input v-model:value="form.name" @blur="textTrim('name')" />
      </a-form-item>
      <a-form-item label="目录" name="folder">
        <a-input v-model:value="form.folder" placeholder="" readonly>
          <template #suffix>
            <FolderOpenOutlined @click="folderSelectShow=true" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item label="链接规则">
        <a-space direction="vertical" style="width: 100%;">
          <a-select v-model:value="form.mediaType" style="width:100%" allowClear>
            <a-select-option value="movie">电影</a-select-option>
            <a-select-option value="tv">剧集</a-select-option>
          </a-select>
          <a-input v-model:value="form.rules.genre_ids">
            <template #addonBefore>
              <div style="width: 60px">内容类型</div>
            </template>
            <template #suffix>
              <InfoCircleOutlined @click="showRules(0)" />
            </template>
          </a-input>
          <a-input v-model:value="form.rules.origin_country">
            <template #addonBefore>
              <div style="width: 60px">国家/地区</div>
            </template>
            <template #suffix>
              <InfoCircleOutlined @click="showRules(2)" />
            </template>
          </a-input>
          <a-input v-model:value="form.rules.original_language">
            <template #addonBefore>
              <div style="width: 60px">语种</div>
            </template>
            <template #suffix>
              <InfoCircleOutlined @click="showRules(1)" />
            </template>
          </a-input>
        </a-space>
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-textarea v-model:value="form.description" :rows="3" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 路径选择 -->
  <a-modal v-model:visible="folderSelectShow" title="选择目录" @ok="getSelectedFolder">
    <FileSelector ref="refFileSelector" />
  </a-modal>

  <a-drawer width="30%" placement="right" v-model:visible="rulesShow" :mask="false" :maskClosable="false">
    <a-table v-show="rulesShowIndex === 0" :columns="ruleCols" :row-key="record => record.id"
      :data-source="rulesContent" size="small" bordered>
    </a-table>
    <a-table v-show="rulesShowIndex === 1" :columns="ruleCols1" :row-key="record => record.id"
      :data-source="rulesContent1" size="small" bordered>
      <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
        <div style="padding: 8px">
          <a-input :value="selectedKeys[0]" style="width: 188px; margin-bottom: 8px; display: block"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="confirm" />
        </div>
      </template>
    </a-table>
    <a-table v-show="rulesShowIndex === 2" :columns="ruleCols2" :row-key="record => record.id"
      :data-source="rulesContent2" size="small" bordered>
      <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
        <div style="padding: 8px">
          <a-input :value="selectedKeys[0]" style="width: 188px; margin-bottom: 8px; display: block"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="confirm" />
        </div>
      </template>
    </a-table>
  </a-drawer>
</template>

<script>
import api from '../../api/api.js'
import { FolderOpenOutlined } from '@ant-design/icons-vue'
import FileSelector from '../components/FileSelector.vue'
import { ref } from 'vue';
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { moveGenres, tvGenres, languages, countries } from './rules.js'

export default {
  name: 'LibraryAdd',
  components: {
    InfoCircleOutlined,
    FolderOpenOutlined,
    FileSelector
  },
  props: {
    modelData: Object,
    success: Function,
    failure: Function
  },
  setup() {
    const refFileSelector = ref()
    const folderSelected = () => {
      return refFileSelector.value.selectedKeys
    }
    return {
      refFileSelector, folderSelected
    }
  },
  data() {
    return {
      module: 'library',
      isShow: false, loading: false, folderSelectShow: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      form: {
        id: '',
        name: '',
        folder: '',
        description: '',
      },
      rules: {
        name: [
          { required: true, message: '请填写媒体库名称', trigger: 'blur' },
          { max: 10, message: '长度需10以内', trigger: 'blur' },
        ],
        folder: [
          { required: true, message: '请选择目录', trigger: 'blur' },
          // { max: 20, message: '长度需为20以内', trigger: 'blur' },
        ],
        description: [
          { max: 100, message: '长度需为100以内', trigger: 'blur' },
        ],
      },
      rulesShow: false, rulesShowIndex: 0,
      ruleCols: [
        {
          title: '值',
          dataIndex: 'id',
          align: 'center',
          width: '30%',
        },
        {
          title: '名称',
          dataIndex: 'name',
          align: 'center',
          width: '40%',
          onFilter: (value, record) => record.type.includes(value),
        },
        {
          title: '电影/电视剧',
          dataIndex: 'type',
          key: 'type',
          align: 'center',
          width: '40%',
          filters: [{
            text: '电影',
            value: '电影',
          }, {
            text: '电视剧',
            value: '电视剧',
          }],
          // filteredValue: filtered.type || null,
          onFilter: (value, record) => record.type.includes(value),
          filterSearch: true,
        },
      ], rulesContent: [],
      ruleCols1: [
        {
          title: '值',
          dataIndex: 'iso_639_1',
          align: 'center',
          width: '30%',
        },
        {
          title: '英文名称',
          dataIndex: 'english_name',
          key: 'english_name',
          align: 'center',
          width: '40%',
          customFilterDropdown: true,
          onFilter: (value, record) =>
            !value || record.english_name.toString().toLowerCase().includes(value.toLowerCase()),
        },
        {
          title: '名称',
          dataIndex: 'name',
          align: 'center',
          width: '40%',
        },
      ], rulesContent1: [],
      ruleCols2: [
        {
          title: '值',
          dataIndex: 'iso_3166_1',
          align: 'center',
          width: '30%',
        },
        {
          title: '英文名称',
          dataIndex: 'english_name',
          align: 'center',
          width: '40%',
        },
        {
          title: '名称',
          dataIndex: 'native_name',
          key: 'native_name',
          align: 'center',
          width: '40%',
          customFilterDropdown: true,
          onFilter: (value, record) =>
            !value || record.native_name.toString().toLowerCase().includes(value.toLowerCase()),
        },
      ], rulesContent2: [],
    }
  },
  methods: {
    open(form) {
      this.form = form
      if (!form.rules) {
        this.form.rules = {
          genre_ids: '',
          original_language: '',
          origin_country: '',
        }
      }
      this.isShow = true
    },
    textTrim(col) {
      this.form[col] = this.form[col] ? this.form[col].trim() : ''
      //   console.log(`'${this.form[col]}'`)
    },
    getSelectedFolder() {
      this.form.folder = this.folderSelected()[0]
      this.folderSelectShow = false
    },
    doSave() {

      // console.log('values', this.form);return;

      this.$refs.form
        .validate()
        .then(() => {
          // console.log('values', this.form);
          this.loading = true
          !this.form.mediaType && (this.form.mediaType = null)
          api.save(this.module, {...this.form, rules: JSON.stringify(this.form.rules)}).then(response => {
            if (response.data.code === 1) {
              this.isShow = false
              this.form = {
                rules: {
                  genre_ids: '',
                  original_language: '',
                  origin_country: '',
                }
              }
              this.$message.success('保存成功')
              // 回调
              this.$nextTick(() => {
                this.success && this.success()
              })
            } else {
              this.$message.error(`保存失败：${response.data.message}`)
              // 
              this.failure && this.failure()
            }
          }).catch((error) => {
            this.$message.error(`保存失败：${error.message}`)
          }).then(() => {
            this.loading = false
          })
        })
        .catch(error => {
          console.log('error', error);
        })
    },
    showRules(contentType) {
      this.rulesShowIndex = contentType
      if (contentType === 0) {
        if (!this.rulesContent.length) {
          this.rulesContent = moveGenres.map(o => {
            o.type = '电影'
            return o
          }).concat(
            tvGenres.map(o => {
              o.type = '电视剧'
              return o
            })
          )
        }
      } else if (contentType === 1) {
        !this.rulesContent1.length && (this.rulesContent1 = languages)
      } else if (contentType === 2) {
        !this.rulesContent2.length && (this.rulesContent2 = countries)
      }
      this.rulesShow = true
    }
  }
}
</script>